package fr.upmc.contact;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.RawContacts.Entity;
import android.widget.ArrayAdapter;
import fr.upmc.contact.model.Contact;

public class ContactRequest extends AsyncTask<Void, Contact, Void> implements OnCancelListener {

	/**
	 * The Controller on Data and View
	 */
	private ArrayAdapter<Contact> adpater;

    
    /**
     * Constructor with Adapter Controller
     * @param adapter
     */
    public ContactRequest(ArrayAdapter<Contact> adapter){
    	this.adpater = adapter;
    }

    
    /**
     * Operation do in background by another Thread
     * If you want to update GUI, you must use operation publishProgress
     */
	@Override
	protected Void doInBackground(Void... sringtUrl) {

	    	/* SQL Request to database Contact
	    	 *   NOTE : you can make one query by table and one table has a URI
	    	 */
	    	ContentResolver cr = adpater.getContext().getContentResolver();
			Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, // The Access to the table
					null, // Projection of Column to get (NULL == ALL)
					null, // Filtering data
					null, // Selection arguments
					ContactsContract.Contacts.DISPLAY_NAME); // Ordering data by
			/* Check and parse the result with a CURSOR of datas */
			if (cur.getCount() > 0) {
				/* While there are datas */
				while (cur.moveToNext()) {
					Contact c = new Contact();
					/**
					 * CONTACT TABLES :
					 *   _ID 				= User identification
					 *   DISPLAY_NAME 		= Complete name of user
					 *   IN_VISIBLE_GROUP 	= User is visible ?
					 *   PHOTO_ID			= User has a photo id (null if no else the id number access)
					 * RAW  CONTACTS TABLES :
					 * This table allows to get all information of a Contact identified by _ID
					 *   ACCOUNT_TYPE = The type of account user (sim,phone,google ...)
					 */
					String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
					String visible = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.IN_VISIBLE_GROUP));
					String p_id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
					c.setFirstname(name);
					/* Check Contact has a photo */
					if (p_id != null){
						Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
					            .parseLong(id));
						c.setPhoto(Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY));
					}
					else{
						c.setPhoto(null);
					}
					/* Check information of account user
					 * Here we want to filter accounts of SIM card
					 */
					Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, Long.parseLong(id));
					Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY);
					boolean insert = true;
					 Cursor cc = cr.query(entityUri,
					          new String[]{RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, RawContacts.ACCOUNT_TYPE},
					          null, null, null);
					 	if (cc != null){
						 	if (cc.getCount() > 0){
						 		cc.moveToNext();
						    	if (cc.getString(3).equalsIgnoreCase("vnd.sec.contact.sim")){
						    		insert = false;
						    	}
						     }
					 	}
					/* Adding Contact */
					if (visible.equalsIgnoreCase("1") && insert){
						/* Update GUI by publishing */
						this.publishProgress(c);
					}
				}
			}
			return null;
	    }
	
	/**
	 * Execute by the GUI Main thread for update the GUI if necessary
	 */
	@Override
	protected void onProgressUpdate(Contact... values) {
		/* Initialize the view */
		for (Contact c : values){
			adpater.add(c);
		}
		super.onProgressUpdate(values);
	}
	
	/**
	 * Execute by the GUI Main Thread for update the GUI when works is completed
	 */
	@Override
	protected void onPostExecute(Void result) {
		//dialog.dismiss();
		super.onPostExecute(result);
	}
	
	/**
	 * Execute by the GUI Main Thread in case of canceled the Thread Operation
	 */
	public void onCancel(DialogInterface arg0) {
		/* When ProgressBar is canceled by user (by button BackPressed) */
		/* Abort the thread if running */
		cancel(true);
		
	}
	
	/**
	 * Execute by the GUI Main Thread on the beginning execution task
	 */
	@Override
	protected void onPreExecute() {
		/*dialog = ProgressDialog.show(this.adpater.getContext()
	    		, "Working in progress"
	    		, "request information to database contact of phone"
	    		, true
	    		, true
	    		, this);*/
		super.onPreExecute();
	}

}
